from flask import Flask, session, g
import config
from exts import db, mail
from models import UserModel
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp
from flask_migrate import Migrate

app = Flask(__name__)
# 绑定配置文件
app.config.from_object(config)

# 先创建对象再绑定
db.init_app(app)
mail.init_app(app)

migrate = Migrate(app, db)

# blueprints 用来做模块，模块注册
app.register_blueprint(qa_bp)
app.register_blueprint(auth_bp)


# before_request/ nefore_first_request/ after_request 钩子函数（拦截器）
# hook
@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    if user_id:
        user = UserModel.query.get(user_id)
        # 给 g（全局变量）设置属性
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)


# 上下文处理器，帮助页面信息渲染，不需要每次请求页面都要渲染用户信息
@app.context_processor
def my_contex_processor():
    return {"user": g.user}


if __name__ == '__main__':
    app.run()
